package com.kindle.convert.txt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * 把不标准的Txt文件转化为可以支持目录的txt模板
 * 每一节或每一章前加上 "第?章"
 * @author ibm
 *
 */

public class TxtProcess {
	
	private String sourceFile = "";
	private String destFile = "";
	
	public void initFilePath(String sour, String dest){
		this.sourceFile = sour;
		this.destFile = dest;
	}
	
	public void process(){
		int i=0,j=0;
		String[] titles = new String[200];
		boolean getTitles = false,start = false; 
		String line = "";
		
		BufferedReader br= null;
		FileWriter fw = null;
		
		try{
			br = new BufferedReader(new FileReader(new File(sourceFile)));
			fw = new FileWriter(destFile);
			while(br.ready()){
				line = br.readLine();
				
				//先得到标题
				if(!getTitles){
					if(line.trim().equals("封面")){
						start = true;
						continue;
					}
					
					if(line.trim().equals("后记")){
						getTitles = true;
						continue;
					}
					
					if(start){
						titles[i++]=line.trim();
					}
				}else{
					//把正文部分的标题改掉
					if(j<i && line.trim().equals(titles[j])){
						j++;
						fw.write("第"+j+"章   "+line+"\r\n");
					}else{
						fw.write(line+"\r\n");
					}
				}				
			}
			fw.close();
			br.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TxtProcess tp = new TxtProcess();
		tp.initFilePath("resource\\in.txt", "resource\\out.txt");
		tp.process();
	}

}
